#include "usart.h"
#include "modbus.h"
#include "tim.h"

/*******************************************************************************
*超时接口
*******************************************************************************/
void TIM4_IRQHandler(void)
{
  /* USER CODE BEGIN TIM4_IRQn 0 */
  MsTimeout(&Ms1);
  /* USER CODE END TIM4_IRQn 0 */
  HAL_TIM_IRQHandler(&htim4);
  /* USER CODE BEGIN TIM4_IRQn 1 */

  /* USER CODE END TIM4_IRQn 1 */
}

/*******************************************************************************
*modbus从机接口
*******************************************************************************/
unsigned char uart1Buff[200];
ModbusSlaveObj_t Ms1;
void SerialWrite(unsigned char *buff,int length)
{
	HAL_UART_Transmit(&huart1,buff,length,1000);
}

/*******************************************************************************
*modbus从机串口接收
*******************************************************************************/
extern DMA_HandleTypeDef hdma_usart1_rx;
void USART1_IRQHandler(void)
{
	if(__HAL_UART_GET_FLAG(&huart1,UART_FLAG_IDLE))
	{
		__HAL_UART_CLEAR_IDLEFLAG(&huart1);
		int len = 200 - hdma_usart1_rx.Instance->CNDTR;
		HAL_UART_DMAStop(&huart1);
		MsSerialRead(&Ms1,uart1Buff,len);
		HAL_UART_Receive_DMA(&huart1,uart1Buff,200);
	}
}
/*******************************************************************************
*modbus任务
*******************************************************************************/
short _cmdBuff[30];
void main()
{
	static char isCfg = 0;
	if(isCfg == 0)
	{
		isCfg = 1;
		MsInit(&Ms1,1,5,SerialWrite);
		MsConfigureRegister(&Ms1,0x03,_cmdBuff,sizeof(_cmdBuff) / 2);
		MsConfigureRegister(&Ms1,0x06,_cmdBuff,sizeof(_cmdBuff) / 2);
		MsConfigureRegister(&Ms1,0x10,_cmdBuff,sizeof(_cmdBuff) / 2);
	}
	else
	{
		MsProcess(&Ms1);
        HAL_Delay(5);
	}	
}